package top.meijhm.communitymanagement.common.auth.api;

import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;
import top.meijhm.communitymanagement.common.auth.jwt.JwtUtils;
import top.meijhm.communitymanagement.common.auth.model.LoginUser;
import top.meijhm.communitymanagement.common.auth.model.Result;
import top.meijhm.communitymanagement.common.exceptions.UnAuthorizedException;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "*")
@Api(
        value = "/login",
        consumes = "application/json",
        produces = "application/json",
        description = "用户登录认证"
)
public class AuthController {
    @Autowired
    private JwtUtils jwtUtils;

    @Qualifier("authenticationManagerBean")
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/auth")
    @ApiOperation(
            value = "登录认证",
            notes = "传入登录用户信息，返回登录用户的详细信息和认证Token,认证Token位于响应头的Authorization中." +
                    "其它的API请求必须在请求头Authorization头中放置Token进行认证."
    )
    public Result login(
            @ApiParam(value = "登录用户名/密码/验证码/userKey", name = "LoginUser", required = true)
            @RequestBody LoginUser loginUser,
            @RequestParam(name = "code") String code, @RequestParam(name = "userKey") String userKey,
            HttpServletResponse response) throws UnAuthorizedException {
        /* 在这里验证用户名和密码，验证成功则生成token返回 */
        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginUser.getUsername(),
                            loginUser.getPassword()
                    )
            );
        } catch (AuthenticationException e) {
            throw new UnAuthorizedException("Username or Password error.");
        }

        String token = jwtUtils.generateToken(loginUser.getUsername());  // 生成 Token，返回给客户端
        log.debug("Token: " + token);
        return Result.succeed(MapUtil.builder().put(jwtUtils.HEADER_STRING, token).build());
    }
}